const gulp = require('gulp');
const colors = require('colors');

gulp.task('check-client-h5', (cb) => {
	const through = require('through2');
	const msg = [];
	return gulp.src(['src-h5/*/zj-**/a*.ts'])
		.pipe(through.obj(function (file, encode, callback) {
			if (/^import\s+.*\s+from\s+['|"]@feidao\/web\/atom\/nodejs\/.*['|"]/m.test(file.contents.toString())) {
				const str = file.contents.toString().match(/import\s+.*\s+from\s+['|"]@feidao\/web\/atom\/nodejs\/.*['|"]/).toString();
				msg.push(`\n客户端不能引入服务端的原子操作 ${file.path} 中引入了服务端原子操作  ${str}\n`);
			}
			callback();
		}, function () {
			if (msg.length > 0) {
				console.error(colors.yellow(`客户端原子操作引用错误:`));
				console.error(colors.red(msg.toString()));
				throw new Error('客户端原子操作引用错误');
			} else {
				cb();
			}
		}))
});

gulp.task('check-client-web', (cb) => {
	const through = require('through2');
	const msg = [];
	return gulp.src(['src-web/*/zj-**/a*.ts'])
		.pipe(through.obj(function (file, encode, callback) {
			if (/^import\s+.*\s+from\s+['|"]@feidao\/web\/atom\/nodejs\/.*['|"]/m.test(file.contents.toString())) {
				const str = file.contents.toString().match(/import\s+.*\s+from\s+['|"]@feidao\/web\/atom\/nodejs\/.*['|"]/).toString();
				msg.push(`\n客户端不能引入服务端的原子操作 ${file.path} 中引入了服务端原子操作  ${str}\n`);
			}
			callback();
		}, function () {
			if (msg.length > 0) {
				console.error(colors.yellow(`客户端原子操作引用错误:`));
				console.error(colors.red(msg.toString()));
				throw new Error('客户端原子操作引用错误');
			} else {
				cb();
			}
		}))
});

gulp.task('check-service-web', (cb) => {
	const through = require('through2');
	const msg = [];
	return gulp.src(['src-web/*/na*.ts', 'src-web/*/zj-**/na*.ts'])
		.pipe(through.obj(function (file, encode, callback) {
			if (/^import\s+.*\s+from\s+['|"]@feidao\/web\/atom\/browser\/.*['|"]/m.test(file.contents.toString())) {
				const strs = file.contents.toString().split('\n');
				strs.forEach((item, i) => {
					if (item.match(/import\s+.*\s+from\s+['|"]@feidao\/web\/atom\/browser\/.*['|"]/)) {
						const str = file.contents.toString().match(/import\s+.*\s+from\s+['|"]@feidao\/web\/atom\/browser\/.*['|"]/).toString();
						msg.push(`\n服务端不能引入客户端端的原子操作 ${file.path + ':' + (i + 1)} 中引入了客户端原子操作  ${str}\n`);
					}
				});
			}
			callback();
		}, function () {
			if (msg.length > 0) {
				console.error(colors.yellow(`服务端原子操作引用错误:`));
				console.error(colors.red(msg.toString()));
				throw new Error('服务端原子操作引用错误');
			} else {
				cb();
			}
		}))
});

gulp.task('check-service-h5', (cb) => {
	const through = require('through2');
	const msg = [];
	return gulp.src(['src-h5/*/na*.ts', 'src-h5/*/zj-**/na*.ts'])
		.pipe(through.obj(function (file, encode, callback) {
			if (/^import\s+.*\s+from\s+['|"]@feidao\/web\/atom\/browser\/.*['|"]/m.test(file.contents.toString())) {
				const strs = file.contents.toString().split('\n');
				strs.forEach((item, i) => {
					if (item.match(/import\s+.*\s+from\s+['|"]@feidao\/web\/atom\/browser\/.*['|"]/)) {
						const str = file.contents.toString().match(/import\s+.*\s+from\s+['|"]@feidao\/web\/atom\/browser\/.*['|"]/).toString();
						msg.push(`\n服务端不能引入客户端端的原子操作 ${file.path + ':' + (i + 1)} 中引入了客户端原子操作  ${str}\n`);
					}
				});
			}
			callback();
		}, function () {
			if (msg.length > 0) {
				console.error(colors.yellow(`服务端原子操作引用错误:`));
				console.error(colors.red(msg.toString()));
				throw new Error('服务端原子操作引用错误');
			} else {
				cb();
			}
		}))
});

gulp.task('check-service', (cb) => {
	const through = require('through2');
	const msg = [];
	return gulp.src(['service/src/*.ts'])
		.pipe(through.obj(function (file, encode, callback) {
			if (/^import\s+.*\s+from\s+['|"]@feidao\/web\/atom\/browser\/.*['|"]/m.test(file.contents.toString())) {
				const str = file.contents.toString().match(/import\s+.*\s+from\s+['|"]@feidao\/web\/atom\/browser\/.*['|"]/).toString();
				msg.push(`\n服务不能引入客户端的原子操作${file.path} 中引入了客户端原子操作  ${str}\n`);
			}
			callback();
		}, function () {
			if (msg.length > 0) {
				console.error(colors.yellow(`服务端原子操作引用错误:`));
				console.error(colors.red(msg.toString()));
				throw new Error('服务端原子操作引用错误');
			} else {
				cb();
			}
		}))
});

gulp.task('check-widgets', (cb) => {
	const through = require('through2');
	const path = require('path');
	const errs = [];
	return gulp.src(['src-h5/**/b.ts', 'src-web/**/b.ts'])
		.pipe(through.obj(function (file, encode, callback) {
			const widgets = [];
			const dir = path.dirname(file.path);
			const centents = file.contents.toString().split('\n');
			centents.forEach((centent, i) => {
				if (/^import\s+['|"]@feidao\/widgets\/fd-[wh]{1,2}[0-9]+['|"]/.test(centent)) {
					const no = centent.match(/fd-[a-z]{1,2}[0-9]+/m).toString();
					widgets.push({
						no,
						path: `${file.path}:${++i}`
					});
				}
			});
			gulp.src([`${dir}/html.ts`, `${dir}/tpl.ts`, `${dir}/P*.ts`, `${dir}/p*.ts`, `${dir}/zj-**/tpl.ts`, `${dir}/zj-**/P*.ts`, `${dir}/zj-**/p*.ts`], {
				allowEmpty: true
			})
				.pipe(through.obj(function (file, encode, cb) {
					const centents = file.contents.toString();
					widgets.forEach((widget) => {
						if (!widget.used && centents.match(widget.no, 'mg')) {
							widget.used = true;
						}
					});
					cb();
				}, function () {
					errs.push(...widgets.filter((widget) => {
						return !widget.used;
					}).map((widget) => {
						return `${widget.path} 定义的控件未被使用`;
					}));
					callback();
				}));
		}, function () {
			if (errs.length > 0) {
				console.error(colors.yellow(`控件引用错误:`));
				console.error(colors.red(errs.join('\n')));
				throw new Error('控件引用错误');
			} else {
				cb();
			}
		}));
});

gulp.task('check-send_msg', (cb) => {
	const through = require('through2');
	const arr = [];
	return gulp.src(['service/src/*.ts'])
		.pipe(through.obj(function (file, encode, callback) {
			if (/send_msg/m.test(file.contents.toString())) {
				const strs = file.contents.toString().split('\n');
				strs.forEach((item, i) => {
					if (item.match(/send_msg/m)) {
						arr.push(file.path + ':' + (i + 1) + '\t 服务中不能引用send_msg 请手动删除');
					}
				});
			}
			callback();
		}, function () {
			if (arr.length > 0) {
				console.error(colors.yellow(`错误的方法调用:`));
				console.error(colors.red(arr.join('\n')));
				throw new Error('错误的方法调用');
			} else {
				cb();
			}
		}))
});

gulp.task('check-folder-web-h5', (cb) => {
	const glob = require('glob');
	glob('src-web/*', function (er, files) {
		const web_folders = new Set(files.map((item) => {
			return item.match(/.*\/(.*)/)[1];
		}));
		const glob = require('glob');
		glob('src-h5/*', function (er_h5, files) {
			if (!files) {	// ??? some times this would be null?
				return;
			}
			const dump = files.map((item) => {
				return item.match(/.*\/(.*)/)[1];
			}).filter((it) => {
				return web_folders.has(it);
			});
			if (dump.length > 0) {
				console.error(colors.yellow(`src-web与src-h5文件夹名称冲突:`));
				console.error(colors.red(dump.join('\n')));
				throw new Error('文件夹名称冲突')
			} else {
				cb();
			}
		});
	})
});

gulp.task('check-folder-web-wxapp', (cb) => {
	const glob = require('glob');
	glob('src-web/*', function (er, files) {
		const web_folders = new Set(files.map((item) => {
			return item.match(/.*\/(.*)/)[1];
		}));
		const glob = require('glob');
		glob('src-wx-app/*', function (er_h5, files) {
			if (!files) {	// ??? some times this would be null?
				return;
			}
			const dump = files.map((item) => {
				return item.match(/.*\/(.*)/)[1];
			}).filter((it) => {
				return web_folders.has(it);
			});
			if (dump.length > 0) {
				console.error(colors.yellow(`src-web与src-wx-app文件夹名称冲突:`));
				console.error(colors.red(dump.join('\n')));
				throw new Error('文件夹名称冲突')
			} else {
				cb();
			}
		});
	})
});

gulp.task('check-folder-h5-wxapp', (cb) => {
	const glob = require('glob');
	glob('src-h5/*', function (er, files) {
		const web_folders = new Set(files.map((item) => {
			return item.match(/.*\/(.*)/)[1];
		}));
		const glob = require('glob');
		glob('src-wx-app/*', function (er_h5, files) {
			if (!files) {	// ??? some times this would be null?
				return;
			}
			const dump = files.map((item) => {
				return item.match(/.*\/(.*)/)[1];
			}).filter((it) => {
				return web_folders.has(it);
			});
			if (dump.length > 0) {
				console.error(colors.yellow(`src-h5与src-wx-app文件夹名称冲突:`));
				console.error(colors.red(dump.join('\n')));
				throw new Error('文件夹名称冲突')
			} else {
				cb();
			}
		});
	})
});

gulp.task('check-folder', gulp.parallel('check-folder-web-h5', 'check-folder-web-wxapp', 'check-folder-h5-wxapp'));

gulp.task('check-atoms', gulp.parallel('check-client-web', 'check-client-h5', 'check-service-web', 'check-service-h5', 'check-service'));

gulp.task('default', gulp.parallel('check-folder', 'check-atoms', 'check-widgets', 'check-send_msg'));
